import React from 'react'
import { Redirect, Route, Switch, useLocation } from 'react-router-dom'
import { publicRoutes } from './publicRoutes'
import { isLogined } from '@/utils/auth'
import adminRoutes from './adminRoutes'

const RouterConfig = () => {
  const location = useLocation()

  // 合并所有的路由
  const allRoutes = publicRoutes.concat(adminRoutes)

  // 拿到当前路径
  let { pathname } = location
  let thisRoute = allRoutes.find((el) => {
    if (el.routes) {
      return el.routes.find((els) => {
        if (els.routes) {
          return els.routes.find((elss) => elss['path'] === pathname)
        }
        return els['path'] === pathname
      })
    } else {
      return el['path'] === pathname
    }
  })

  // 如果没有登录而且页面为登录页的时候渲染登录页
  if (pathname === '/login' && !isLogined()) {
    return <Route path={pathname} component={thisRoute!['component']} exact />
  }

  // 如果已经登录渲染其他页面
  if (isLogined()) {
    if (pathname === '/login' || pathname === '/') {
      return <Redirect to='/admin/base' />
    }

    // 判断路由是否存在 存在就渲染
    if (thisRoute) {
      if (thisRoute.routes) {
        return (
          <thisRoute.component routes={thisRoute.routes}>
            {thisRoute.routes.map((rou) => {
              if (rou.routes) {
                return (
                  <Switch key={rou.path}>
                    {rou.routes.map((adrs) => {
                      return <Route key={adrs.path} {...adrs} />
                    })}
                  </Switch>
                )
              } else {
                return <Route key={rou.path} {...rou} />
              }
            })}
          </thisRoute.component>
        )
      }
      return <Route path={pathname} component={thisRoute['component']} exact />
    } else {
      return <Redirect to='/404' />
    }
  } else {
    return <Redirect to='/login' />
  }
}

export default RouterConfig
